import axios from 'axios';
import router from './router';
import config from './config'
import {
    Loading,
    Message
} from 'element-ui'
import store from 'store';


let http = axios.create({
    baseURL: config.api + 'api',
    timeout: 20000
});

let loading;
let timeout;
let delay = 300;

http.interceptors.request.use(function (config) {
    let token = store.get('token')

    if (token) {
        config.headers['Authorization'] = token
    }

    if (timeout) {
        clearTimeout(timeout)
        timeout = null
    }

    timeout = setTimeout(() => {

        loading = Loading.service({
            fullscreen: true,
            text: '请求中...'
        });

    }, delay)

    return config;
}, function (err) {
    return Promise.reject(err);
});

http.interceptors.response.use(function (response) {
    if (timeout) {
        clearTimeout(timeout)
        timeout = null
    }
    loading ? loading.close() : '';

    if (!response.data.status) {
        Message({
            message: response.data.msg,
            type: 'error'
        })
        return Promise.reject(response.data.msg);
    }

    return response.data.data
}, function (err) {
    if (timeout) {
        clearTimeout(timeout)
        timeout = null
    }
    loading ? loading.close() : '';

    if (err.response.status == 403) {
        Message({
            message: '登录失效，请重新登录',
            type: 'error'
        })
        router.push('/login');
    }
    return Promise.reject(err);
});

export default http;
